package com.zhu.esyblog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhu.esyblog.Utils.BeanCopyUtils;
import com.zhu.esyblog.pojo.RespBean;
import com.zhu.esyblog.pojo.Tag;
import com.zhu.esyblog.mapper.TagMapper;
import com.zhu.esyblog.service.ITagService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhu.esyblog.vo.TagVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author stx
 * @since 2022-06-22
 */
@Service
public class TagServiceImpl extends ServiceImpl<TagMapper, Tag> implements ITagService {
    @Autowired
    private TagMapper tagMapper;
    /**
     * 根据文章id寻找Tag
     * @param articleId
     * @return
     */
    @Override
    public List<TagVo> findTagsByArticleId(Long articleId) {
        List<Tag> tags= tagMapper.findTagsByArticleId(articleId);
        return copyList(tags);
    }

    @Override
    public RespBean hots(int limit) {

        //按照tag拥有最对文章数量查询
        List<Long> tagIds= tagMapper.findHotsTagIds(limit);
        if(CollectionUtils.isEmpty(tagIds)){
            return RespBean.success("success",Collections.emptyList());
        }
        List<Tag> tagList = tagMapper.selectBatchIds(tagIds);
//        List<TagVo> tagVoList = BeanCopyUtils.copyBeanList(tags, TagVo.class);
        return  RespBean.success("success",tagList);
    }

    @Override
    public RespBean getAllTags() {
        LambdaQueryWrapper<Tag> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(Tag::getId,Tag::getTagName);
        List<Tag> tagList = tagMapper.selectList(queryWrapper);
        List<TagVo> tagVoList = BeanCopyUtils.copyBeanList(tagList, TagVo.class);
        return RespBean.success("success",tagVoList);
    }

    @Override
    public RespBean findAllDetail() {
        List<Tag> tagList = tagMapper.selectList(new LambdaQueryWrapper<>());
        List<TagVo> tagVoList = BeanCopyUtils.copyBeanList(tagList, TagVo.class);
        return RespBean.success("success",tagVoList);
    }

    @Override
    public RespBean findAllDetailById(Long id) {

         Tag tag = tagMapper.selectById(id);
         TagVo tagVo = BeanCopyUtils.copyBean(tag, TagVo.class);
         return RespBean.success("success",tagVo);
    }

    public TagVo copy(Tag tag){
        TagVo tagVo=new TagVo();
        BeanUtils.copyProperties(tag,tagVo);
        return tagVo;
    }

    public List<TagVo> copyList(List<Tag> tagList){
        List<TagVo> tagVoList=new ArrayList<>();
        for (Tag tag : tagList) {
            tagVoList.add(copy(tag));
        }
        return tagVoList;
    }



}
